package com.test.demo.conf;

import com.test.demo.service.MyAuthProvider;
import com.test.demo.service.MyDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

/**
 * @author 51599
 */
@Configuration
@EnableWebSecurity//适配器设置
public class MyWebSecurityAdept extends WebSecurityConfigurerAdapter {

//  基于session登录
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        /*auth.inMemoryAuthentication()
                .withUser("123").password("123").roles("admin")
                .and()
                .withUser("321").password("321").roles("user")

                ;*/
                auth
                        //自定义 loadUserByUsername
                        .userDetailsService(new MyDetailsService())
                .and()
                .authenticationProvider(new MyAuthProvider())
                ;
                        /*.jdbcAuthentication()
                .dataSource(dataSource)
                .getUserDetailsService();*/
        //注册用户
      /*  boolean xxx = manage.userExists("XXX");
        if (!xxx){
            manage.createUser(User.withUsername("xishi").password(new BCryptPasswordEncoder().encode("123")).build());
        }*/
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http
                //列些地而受行
                .authorizeRequests()//所有请求都需要验证
                .anyRequest( ).authenticated().and( )
                .formLogin()
                .and()
                //cookies 不一定时浏览器token，集群会话 第三方、无会话
                .rememberMe()
                .and()
                .csrf( ).disable();
/*                //那些可以登录
                .authorizeRequests()
                //忽略静态支援
                .antMatchers("img/**")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                //登录名单
                .formLogin()
                //.loginPage("login.html")
                .loginProcessingUrl("/login")
                //登录的成功跳转页面
                .defaultSuccessUrl("/")
                //失败重定向地址
                .failureForwardUrl("/login.html?erro")
                //配置登录页表单
                .passwordParameter("oo")
                .usernameParameter("xx")
                //失败异常处理
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                        exception.printStackTrace();
                        request.getRequestDispatcher(request.getRequestURI().toString())
                                .forward(request,response);
                    }
                })
                .permitAll()
                .and()
                //默认所有depost请求都会拦截
                .csrf()
                .csrfTokenRepository(new HttpSessionCsrfTokenRepository());
        new BCryptPasswordEncoder().encode("密码");*/
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Autowired
    DataSource dataSource;
    @Bean
    public UserDetailsService userDetailsService(){
        //基于内存存储用户
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        //使用 用户名找user对象
        //manager.loadUserByUsername(use)
       // manager.changePassword();


        //基于jdbc
        JdbcUserDetailsManager manager1 = new JdbcUserDetailsManager(dataSource);
        manager1.createUser(User.withUsername("jiafeng").password(new BCryptPasswordEncoder().encode("111")).roles("admin","xxo").build());


        return manager;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/img/**");
    }
}
